import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: ${NAME}
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.07.25 20:26
 *///TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class jsonDemo {
    @Test
    public void readJson() throws JsonProcessingException {

        Dog dog1 = new Dog("wof",3);
        Person person1 = new Person("lee",19, dog1);

        //Person对象转换JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String personStr = objectMapper.writeValueAsString(person1);

        System.out.println(personStr);

    }

    @Test
    public void writeJson() throws JsonProcessingException {

        String str = "{\"name\":\"lee\",\"age\":19,\"dog\":{\"name\":\"wof\",\"age\":3}}";

        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(str, Person.class);

        System.out.println(person.toString());
    }

    @Test
    public void testJson() throws JsonProcessingException {
        Dog dog1 = new Dog("wof",3);
        Person person1 = new Person("lee",19, dog1);

        List<Person> list = new ArrayList<>();
        list.add(person1);

        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(list);

        System.out.println(s);

    }
}